// pages/exam/success/success.js
const app = getApp()
import utils from '../../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    anwserEnd: {},
    zs: ['https://7zcs.oss-cn-beijing.aliyuncs.com/peixun1.jpg'],
    id: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      anwserEnd: JSON.parse(options.end_data),
      id: options.category_id,
    })
    this.gotCertficate()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  gotCertficate: function() {
    const that = this
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/provider-certificate/provide?access_token=' + accessToken,
        method: 'POST',
        data: {
          category_id: that.data.id,
        },
        header:{
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: res => {
          if(res.data.status === 1) {
            const ctx = wx.createCanvasContext('myCanvas')
            wx.downloadFile({
              url: that.data.zs[0],
              success: res => {
                let rpx = 0
                wx.getSystemInfo({
                  success: res => {
                    rpx = res.windowWidth/375
                  }
                })
                ctx.drawImage(res.tempFilePath, 0, 0,375 * rpx,266 * rpx)
                ctx.setFontSize(12)
                ctx.fillText(that.data.anwserEnd.provider_name, 115 * rpx, 140 * rpx)
                ctx.fillText('保洁项目', 275 * rpx, 140 * rpx)
                ctx.fillText(that.getNowFormatDate(), 240 * rpx, 215 * rpx)
                ctx.draw()
              }
            })
          }
        }
      })
    })
  },

  saveImage: function(e) {
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: res => {
        wx.previewImage({
          urls: [res.tempFilePath],
        })
      }
    }, this)
  },

  getNowFormatDate: function() {
    var date = new Date(),
        seperator1 = '/',
        year = date.getFullYear(),
        month = date.getMonth() + 1,
        strDate = date.getDate()
    if(month >= 1 && month <= 9) {
      month = "0" + month
    }
    if(strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    const currentDate = year + seperator1 + month + seperator1 + strDate
    return currentDate
  }
})